import { defineStore } from 'pinia';
import axios from 'axios';

export const useUserStore = defineStore('user', {
  state: () => ({
    isLoggedIn: false,
    username: '',
    token: ''
  }),
  actions: {
    async login(username, password) {
      try {
        const res = await axios.post('/api/auth/login', { username, password });
        if (res.data.code === 200) {
          this.isLoggedIn = true;
          this.username = res.data.data.username;
          this.token = res.data.data.token;
          localStorage.setItem('token', this.token);
          return true;
        }
        return false;
      } catch (error) {
        console.error('登录失败:', error);
        return false;
      }
    },
    async register(username, password) {
      try {
        const res = await axios.post('/api/auth/register', { username, password });
        if (res.data.code === 200) {
          return true;
        }
        return false;
      } catch (error) {
        console.error('注册失败:', error);
        return false;
      }
    },
    logout() {
      this.isLoggedIn = false;
      this.username = '';
      this.token = '';
      localStorage.removeItem('token');
    }
  }
});
